<?php
namespace plugins\pay\lib\alipay;
use plugins\pay\lib\Pay;
use think\Loader;
use think\Db;
//加载sdk类
Loader::import('AopClient' , PLUGINS_PATH.DS.'pay'.DS.'lib'.DS.'alipay'.DS.'sdk'.DS.'aop' );
Loader::import('AopCertClient' , PLUGINS_PATH.DS.'pay'.DS.'lib'.DS.'alipay'.DS.'sdk'.DS.'aop' );
Loader::import('AlipayTradeAppPayRequest' , PLUGINS_PATH.DS.'pay'.DS.'lib'.DS.'alipay'.DS.'sdk'.DS.'aop'.DS.'request' );
Loader::import('AlipayTradeWapPayRequest' , PLUGINS_PATH.DS.'pay'.DS.'lib'.DS.'alipay'.DS.'sdk'.DS.'aop'.DS.'request' );
Loader::import('AlipayFundTransUniTransferRequest' , PLUGINS_PATH.DS.'pay'.DS.'lib'.DS.'alipay'.DS.'sdk'.DS.'aop'.DS.'request' );
Loader::import('AlipayTradePageRefundRequest' , PLUGINS_PATH.DS.'pay'.DS.'lib'.DS.'alipay'.DS.'sdk'.DS.'aop'.DS.'request' );
Loader::import('AlipayTradeRefundRequest' , PLUGINS_PATH.DS.'pay'.DS.'lib'.DS.'alipay'.DS.'sdk'.DS.'aop'.DS.'request' );
//支付宝支付
class Alipay extends Pay
{
    public $name = '支付宝';
    //支付
    public function expense( $bizcontent ){
        // $aop = new \AopClient;
        // $aop->gatewayUrl = $this->config[ 'alipay_getway' ];
        // $aop->appId = $this->config[ 'appid' ];
        // $aop->rsaPrivateKey = $this->config[ 'app_private_key' ];
        // $aop->alipayrsaPublicKey = $this->config [ 'alipay_public_key' ] ;
        // $aop->format = "json";
        // $aop->charset = "UTF-8";
        // $aop->signType = "RSA2";

        $aop = new \AopCertClient;
        //证书序列号
        $appCertPath = PLUGINS_PATH."pay/lib/alipay/cert/appCertPublicKey.crt";
        //公钥证书
        $alipayCertPath = PLUGINS_PATH."pay/lib/alipay/cert/alipayCertPublicKey_RSA2.crt";
        //支付宝根证书序列号
        $rootCertPath = PLUGINS_PATH."pay/lib/alipay/cert/alipayRootCert.crt";
        $aop->gatewayUrl = $this->config[ 'alipay_getway' ];
        $aop->appId = $this->config[ 'appid' ];
        //私钥
        $aop->rsaPrivateKey = $this->config[ 'app_private_key' ];
        //公钥
        $aop->alipayrsaPublicKey = $this->config [ 'alipay_public_key' ] ;
        // $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset = 'UTF-8';
        $aop->format = 'json';
        //调用getPublicKey从支付宝公钥证书中提取公钥
        $aop->alipayrsaPublicKey = $aop->getPublicKey($alipayCertPath);
        //是否校验自动下载的支付宝公钥证书，如果开启校验要保证支付宝根证书在有效期内
        $aop->isCheckAlipayPublicCert = true;
        //调用getCertSN获取证书序列号
        $aop->appCertSN = $aop->getCertSN($appCertPath);
        //调用getRootCertSN获取支付宝根证书序列号
        $aop->alipayRootCertSN = $aop->getRootCertSN($rootCertPath);
          

        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        $request = new \AlipayTradeWapPayRequest();
        //返回地址
        $url = zy_domain().'/plugin/pay/alipay/noticeurl';
        $request->setNotifyUrl( $url );
        $request->setBizContent($bizcontent);
        $request->setReturnUrl(zy_domain().'/shop/#/pages/Home/home');

        //这里和普通的接口调用不同，使用的是sdkExecute
        $response = $aop->pageExecute($request);
        parent::W( 0 , 'app支付创建成功' , $bizcontent );
        return $response;
        //htmlspecialchars是为了输出到页面时防止被浏览器将关键参数html转义，实际打印到日志以及http传输不会有这个问题
        //echo htmlspecialchars($response);//就是orderString 可以直接给客户端请求，无需再做处理。
    }

    //提现
    public function earning( $bizcontent ){
        $aop = new \AopCertClient;
        //证书序列号
        $appCertPath = PLUGINS_PATH."pay/lib/alipay/cert/appCertPublicKey.crt";
        //公钥证书
        $alipayCertPath = PLUGINS_PATH."pay/lib/alipay/cert/alipayCertPublicKey_RSA2.crt";
        //支付宝根证书序列号
        $rootCertPath = PLUGINS_PATH."pay/lib/alipay/cert/alipayRootCert.crt";
        $aop->gatewayUrl = $this->config[ 'alipay_getway' ];
        $aop->appId = $this->config[ 'appid' ];
        //私钥
        $aop->rsaPrivateKey = $this->config[ 'app_private_key' ];
        //公钥
        $aop->alipayrsaPublicKey = $this->config [ 'alipay_public_key' ] ;
        // $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset = 'UTF-8';
        $aop->format = 'json';
        //调用getPublicKey从支付宝公钥证书中提取公钥
        $aop->alipayrsaPublicKey = $aop->getPublicKey($alipayCertPath);
        //是否校验自动下载的支付宝公钥证书，如果开启校验要保证支付宝根证书在有效期内
        $aop->isCheckAlipayPublicCert = true;
        //调用getCertSN获取证书序列号
        $aop->appCertSN = $aop->getCertSN($appCertPath);
        //调用getRootCertSN获取支付宝根证书序列号
        $aop->alipayRootCertSN = $aop->getRootCertSN($rootCertPath);


        $request = new \AlipayFundTransUniTransferRequest;
        $request->setBizContent($bizcontent);
        $result = $aop->execute ( $request); 
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        if(!empty($resultCode)&&$resultCode == 10000){
            return ['status'=>true,'message'=>'转账成功'];
        } else {
            return ['status'=>false,'message'=>$result->alipay_fund_trans_uni_transfer_response->sub_msg];            
        }       
    }
    
    //支付宝异步回调通知
    public function notify( $post )
    {
        try {
            $aop = new \AopCertClient; 

            //证书路径 
            $alipayCertPath = PLUGINS_PATH."pay/lib/alipay/cert/alipayCertPublicKey_RSA2.crt";
            //支付宝公钥赋值 
            $aop->alipayrsaPublicKey = $aop->getPublicKey($alipayCertPath); 

            $params = $post;

            //签名方式 
            $sign_type="RSA2";

            //验签代码 
            $flag = $aop->rsaCheckV2($params, null, $sign_type);            

        } catch (\Exception $e ) {
            parent::W( 1 , '支付宝支付回调SDK验签异常:'.$e->getMessage() , 'Alipay.php@notify' );
            exit('error');
        }

        //验签成功
        if( $flag ){
            $data = [];
            //支付回调信息
            $data [ 'status' ] = 'failed';
            $data [ 'out_trade_no' ] = $post['out_trade_no'];
            $data [ 'remark' ] = is_array( $post) ? json_encode( $post ) : $post;
            if( $post [ 'trade_status' ] == 'TRADE_SUCCESS' ){
                $data [ 'status' ] = 'success';
            }
            $this->followUpOfCapitalOperation( $data );
            exit( 'success' );
        }
        exit( 'error' );
    }

    // public function notify( $post ){
    //     $aop = new \AopCertClient; 

    //     //证书路径 
    //     $alipayCertPath = PLUGINS_PATH."pay/lib/alipay/cert/alipayCertPublicKey_RSA2.crt";
    //     //支付宝公钥赋值 
    //     $aop->alipayrsaPublicKey = $aop->getPublicKey($alipayCertPath); 

    //     $params = $post;

    //     //签名方式 
    //     $sign_type="RSA2";

    //     //验签代码 
    //     $flag = $aop->rsaCheckV2($params, null, $sign_type);

    //     if ($flag) { 
    //         echo "success"; 
    //     } else { 
    //         echo "fail"; 
    //     }        
    // }


    //退款
    // public function tuikuan()
    public function refund($bizcontent )
    {
        // $aop = new \AopClient ();
        // $aop->gatewayUrl = $this->config[ 'alipay_getway' ];
        // $aop->appId = $this->config[ 'appid' ];
        // $aop->rsaPrivateKey = $this->config[ 'app_private_key' ];
        // $aop->alipayrsaPublicKey = $this->config [ 'alipay_public_key' ] ;
        // $aop->apiVersion = '1.0';
        // $aop->signType = 'RSA2';
        // $aop->postCharset='UTF-8';
        // $aop->format='json';

        $aop = new \AopCertClient;
        //证书序列号
        $appCertPath = PLUGINS_PATH."pay/lib/alipay/cert/appCertPublicKey.crt";
        //公钥证书
        $alipayCertPath = PLUGINS_PATH."pay/lib/alipay/cert/alipayCertPublicKey_RSA2.crt";
        //支付宝根证书序列号
        $rootCertPath = PLUGINS_PATH."pay/lib/alipay/cert/alipayRootCert.crt";
        $aop->gatewayUrl = $this->config[ 'alipay_getway' ];
        $aop->appId = $this->config[ 'appid' ];
        //私钥
        $aop->rsaPrivateKey = $this->config[ 'app_private_key' ];
        //公钥
        $aop->alipayrsaPublicKey = $this->config [ 'alipay_public_key' ] ;
        // $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset = 'UTF-8';
        $aop->format = 'json';
        //调用getPublicKey从支付宝公钥证书中提取公钥
        $aop->alipayrsaPublicKey = $aop->getPublicKey($alipayCertPath);
        //是否校验自动下载的支付宝公钥证书，如果开启校验要保证支付宝根证书在有效期内
        $aop->isCheckAlipayPublicCert = true;
        //调用getCertSN获取证书序列号
        $aop->appCertSN = $aop->getCertSN($appCertPath);
        //调用getRootCertSN获取支付宝根证书序列号
        $aop->alipayRootCertSN = $aop->getRootCertSN($rootCertPath);

        $request = new \AlipayTradeRefundRequest ();
        $request->setBizContent($bizcontent);
        $result = $aop->execute($request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        if(!empty($resultCode)&&$resultCode == 10000){
            return ['return_code'=>'SUCCESS'];
        } else {
            return ['return_code'=>'FAIL','return_msg'=>$result->alipay_trade_refund_response->sub_msg];
        }
    }
}